export default function ({ $axios, $cookies, redirect, store, app, isDev }, inject) {
  // 创建自定义 axios 实例
  const instance = $axios.create({
    timeout: 20000,
    headers: {
      common: { 'Content-Type': 'application/json;charset=UTF-8' }
    },
    withCredentials: true,
    crossDomain: true,
    ...(isDev && process.client
      ? {
          baseURL: '/api/zuche'
        }
      : {})
  });

  const post = (url, params = {}, config = {}) => {
    const language = app.i18n.locale;
    if (language === 'en') params.language = 'en';
    if (language === 'ja') params.language = 'jp';
    if (language === 'zh-Hans' || language === 'zh-Hant') params.language = 'cn';

    return new Promise((resolve, reject) => {
      instance
        .post(url, params, config)
        .then((response) => {
          if (isDev && url === '/user/login' && response.headers.token) {
            console.log('set token', response.headers.token);
            $cookies.set('token', response.headers.token);
          }
          if (config.getAll) {
            resolve(response.data);
          } else {
            resolve(response.data.data);
          }
          if (response.data.code === 0) {
            store.commit('toast/show', response.data.msg || 'fetch error');
          }
        })
        .catch((err) => {
          if (err.response && err.response.status === 401) {
            reject(err);
            store.commit('toast/show', 'please login first');
            store.commit('isLogin', false);
            redirect('/signin?from=' + location.href);
            return;
          }
          if ($axios.isCancel(err)) {
            reject(new Error('Request canceled'));
          } else if (err.message.includes('timeout')) {
            reject(new Error('Request timeout'));
          } else {
            reject(err);
            console.log(
              `[axios error] ${url} ${err?.response?.status || ''} params: ${JSON.stringify(
                params
              )}`
            );
            store.commit('toast/show', 'fetch error' + (err?.response?.status || ''));
          }
        });
    });
  };

  // 注入到 Nuxt 上下文（this.$api）
  inject('api', {
    instance,
    post
  });
}
